package DAO;

import Entities.DoeBookEntity;
import Entities.PurchaseEntity;
import Entities.UserEntity;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.sql.Date;
import java.util.List;


public class PurchaseDao extends HibernateDaoSupport {

    public String getPriceList(String bookId){
        String price = this.getHibernateTemplate().get(DoeBookEntity.class,bookId).getPrice();
        return price;
    }

    public float getBalance(String user_name){
        String balanceStr
                = this.getHibernateTemplate().get(UserEntity.class,user_name).getMoney();
        float balance = Float.parseFloat(balanceStr);
        return balance;
    }

    public boolean updateBalance(String order,String user_name,float money){
        if(order.equals("decrease"))
        {
            UserEntity ue = this.getHibernateTemplate().get(UserEntity.class,user_name);
            String balanceStr = ue.getMoney();
            float balance = Float.parseFloat(balanceStr);
            if(money <= balance)
            {
                balance -= money;
                ue.setMoney(String.valueOf(balance));
                this.getHibernateTemplate().update(ue);
                return true;
            }
            else
            {
                return false;
            }
        }
        else if(order.equals("increase"))
        {
            //6666666
            return true;
        }
        else
        {
            return false;
        }


    }

    //添加订单记录
    public boolean addPurchaseItem(String user_name, String book_id, String purchaseNo, Date date, String count)
    {
        PurchaseEntity pe = new PurchaseEntity();
        pe.setBookId(book_id);
        pe.setCount(count);
        pe.setDate(date);
        pe.setPurchaseNo(purchaseNo);
        pe.setUserName(user_name);
        try {
            this.getHibernateTemplate().save(pe);
            return true;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return false;
    }

    //查询用户订单列表
    public List<PurchaseEntity> purchaseItemQuery(String user_name)
    {
        List<PurchaseEntity> purchaseEntityList = (List<PurchaseEntity>)this.getHibernateTemplate().find("from PurchaseEntity p where userName=?",user_name);

        return purchaseEntityList;

    }

}
